package com.tanhua.dubbo.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.domain.Friend;
import com.tanhua.model.domain.Movement;
import com.tanhua.model.domain.MovementTimeLine;
import com.tanhua.model.dto.MovementDto;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class MovementApiImpl implements MovementApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Override
    public ObjectId publish(MovementDto movementDto) {
        try {
            Movement movement = new Movement();
            movement.setLatitude(movementDto.getLatitude());
            movement.setLocationName(movementDto.getLocation());
            movement.setLongitude(movementDto.getLongitude());
            movement.setUserId(movementDto.getUserId());
            movement.setTextContent(movementDto.getTextContent());
            movement.setMedias(movementDto.getMedias());
            //设置PID
            movement.setPid(idWorker.getNextId("movement"));
            //设置时间
            movement.setCreated(System.currentTimeMillis());
            mongoTemplate.save(movement);
            //
            return movement.getId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public PageResult findByUserId(Long userId, Integer page, Integer pagesize, Integer state) {
        Query query = new Query();
        if (!(userId == null)) {
            query.addCriteria(Criteria.where("userId").is(userId));
        }
        if (!(state == null)) {
            query.addCriteria(Criteria.where("state").is(state));
        }
        long count = mongoTemplate.count(query, Movement.class);
        query.skip((page - 1) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return new PageResult(page, pagesize, (int) count, movements);
    }

    @Override
    public List<Movement> findFriendMovements(Long friendId, Integer page, Integer pagesize) {
        //1、查询好友时间线表
        Query query = Query.query(Criteria.where("friendId").in(friendId))
                .skip((page - 1) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<MovementTimeLine> lines = mongoTemplate.find(query, MovementTimeLine.class);
        //2、提取动态id集合
        List<ObjectId> movementIds = CollUtil.getFieldValues(lines, "movementId", ObjectId.class);
        //3、根据动态id查询动态详情
        Query movementQuery = Query.query(Criteria.where("id").in(movementIds));
        return mongoTemplate.find(movementQuery, Movement.class);
    }

    @Override
    public List<Movement> randomMovements(Integer counts) {

        TypedAggregation aggregation = Aggregation.newAggregation(Movement.class, Aggregation.sample(counts));

        AggregationResults<Movement> movements = mongoTemplate.aggregate(aggregation, Movement.class);

        return movements.getMappedResults();
    }

    @Override
    public List<Movement> findByPids(List<Long> pids) {
        Query query = Query.query(Criteria.where("pId").in(pids));
        return mongoTemplate.find(query, Movement.class);
    }

    @Override
    public void update(ObjectId movementId, Integer state) {
        Query query = Query.query(Criteria.where("id").is(movementId));
        Update update = new Update();
        update.set("state", state);
        mongoTemplate.updateFirst(query, update, Movement.class);
    }

    @Override
    public Movement findById(String movementId) {
        return mongoTemplate.findById(movementId, Movement.class);
    }

    @Override
    public void saveTimeLine(Long userId, ObjectId movementId) {
        //2、查询当前用户的好友数据
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria);
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        if(BeanUtil.isEmpty(friends)){
            return;
        }
        //3、循环好友数据，构建时间线数据存入数据库
        for (Friend friend : friends) {
            MovementTimeLine timeLine = new MovementTimeLine();
            timeLine.setMovementId(movementId);
            timeLine.setUserId(friend.getUserId());
            timeLine.setFriendId(friend.getFriendId());
            timeLine.setCreated(System.currentTimeMillis());
            mongoTemplate.save(timeLine);
        }
    }
}